//
//  WriteData.m
//  FileManageDemo
//
//  Created by shk on 14/12/2.
//  Copyright (c) 2014年 com.shk. All rights reserved.
//

#import "WriteData.h"

@implementation WriteData

{
@protected int i;
}

- (void) runWrite{
    i = 1;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = NSHomeDirectory();
    NSString *filePath = [path stringByAppendingPathComponent:@"temp/oc-file-write-data.txt"];
    BOOL success = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    if(success){
        NSLog(@"Create success");
    }
    
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction:) userInfo:fileHandle repeats:YES];//每个一秒执行一次
}

- (void) timeAction:(NSTimer *) timer{
    
//    static int i = 1;

    NSFileHandle *fileHandle = timer.userInfo;
    NSDate *nowDate = [NSDate date];//获取到当前日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];//设置日期的格式
    NSString *datestring = [dateFormatter stringFromDate:nowDate];
    datestring = [datestring stringByAppendingString:@"\n"];
    NSDate *date = [datestring dataUsingEncoding:NSUTF8StringEncoding];
    [fileHandle writeData:date];
    
    if(i == 10){
        [timer invalidate];//执行10次之后，停止循环
    }
    
    
    i++;
}



@end
